//
//  AppDataBaseManager.m
//  Water
//
//  Created by yh on 2017/11/30.
//  Copyright © 2017年 chenguibang. All rights reserved.
//

#import "AppDataBaseManager.h"
#import <FCFileManager.h>
#import <MJExtension/MJExtension.h>
#import "DBRecord.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <NSDate+YYAdd.h>
#define DATABASE_PATH  [[NSBundle mainBundle] pathForResource:@"water" ofType:@"sqlite"]
#define DATABASE_SHARE_PATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"water.sqlite"]


@implementation AppDataBaseManager
+ (instancetype)shareManager{
    static dispatch_once_t onceToken;
    static AppDataBaseManager *shareInstance = nil;
    dispatch_once(&onceToken, ^{
        shareInstance = [[AppDataBaseManager alloc]init];
    });
    return shareInstance;
}

- (instancetype)init
{
    
    self = [super init];
    if (self) {
        
        if (![FCFileManager existsItemAtPath:DATABASE_SHARE_PATH]) {
            [FCFileManager copyItemAtPath:DATABASE_PATH toPath:DATABASE_SHARE_PATH];
        }
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:DATABASE_SHARE_PATH]) {
            self.dataBaseQueue = [FMDatabaseQueue databaseQueueWithPath:DATABASE_SHARE_PATH];
        }else{
            NSLog(@"文件不存在");
        }
    }
    return self;
}

- (void)addDrinkRecord:(DrinkRecord *)drinkRecord{
    [self.dataBaseQueue inDatabase:^(FMDatabase *db) {
//        [(column1, column2, column3,...columnN)]
//        VALUES (value1, value2, value3,...valueN);
       BOOL result = [db executeUpdate:@"INSERT INTO record (amount, total, time) VALUES (?,?,?)" , @(drinkRecord.amount) ,@(drinkRecord.total) ,drinkRecord.time];
        NSLog(result ? @"插入成功":@"插入失败");
    }];
}



- (void)getTodayRecordscallBack:(void (^)(NSArray *))callBack{
    [self getRecordsWith:[NSDate date] callBack:callBack];
}




- (void)getRecordsWith:(NSDate *)date callBack:(void (^)(NSArray *))callBack{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = date;
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    components.hour = 0;
    components.minute = 0;
    components.second = 0;
    NSDate *startDate = [calendar dateFromComponents:components];
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
    [self getRecordWith:startDate end:endDate callBack:callBack];

}


- (void)getRecordWith:(NSDate *)startTime end:(NSDate *)endTime callBack:(void (^)(NSArray *records))callBack{
    [self.dataBaseQueue inDatabase:^(FMDatabase *db) {
        if (!startTime || !endTime) {
            [SVProgressHUD showErrorWithStatus:@"查询时间有误"];
            return ;
        }
        NSString *start =  [startTime stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *end =  [endTime stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
        FMResultSet *resut =  [db executeQuery:@"SELECT * FROM record WHERE time >= ? AND time < ?" , start, end];
        NSMutableArray *records = [[NSMutableArray alloc]init];
        while ([resut next]) {
            // 每条记录的检索值
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
            for (int i = 0 ; i < resut.columnCount; i ++) {
                NSString *key = [resut columnNameForIndex:i];
                id value = [resut objectForColumnName:key];
                [dict setObject:value forKey:key];
            }
            DBRecord *model = [DBRecord mj_objectWithKeyValues:dict];
            [records addObject:model];
        }
        
        if (callBack) {
            callBack(records);
        }
        
    }];
}

- (void)getTodayDrinkcallBack:(void (^)(int))callBack{
    [self.dataBaseQueue inDatabase:^(FMDatabase *db) {
        
        
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *now = [NSDate date];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
        components.hour = 0;
        components.minute = 0;
        components.second = 0;
        NSDate *startTime = [calendar dateFromComponents:components];
        NSDate *endTime = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startTime options:0];
        
        if (!startTime || !endTime) {
            [SVProgressHUD showErrorWithStatus:@"查询时间有误"];
            return ;
        }
        NSString *start =  [startTime stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *end =  [endTime stringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
        FMResultSet *resut =  [db executeQuery:@"select sum(amount) from record WHERE time >= ? AND time < ?" , start, end];
      
        
        if ([resut next]) {
            if (callBack) {
                callBack([resut intForColumnIndex:0]);
            }
        }
        
    }];
}

//select * from record where strftime('%Y-%m', time) = '2017-12' ; 

@end
